package com.steshov.trainer.utils;

import java.util.ArrayList;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.steshov.trainer.model.Task;

public class DB_Utils {

	public static String DB_NAME = "trainer_db";
	public static String EXERCISE_TAB_NAME = "Exercises";
	public static String TASKS_TAB_NAME = "Tasks";
	public static SQLiteDatabase db;
	public static String[] baseExercises = new String[] { "Пресс", "Отжимание",
			"Присидание", "Уголок", "Прыжки", "Наклоны", "Прогибы" };

	public static void setReady() {
		if (db != null) {

//			 db.execSQL("DROP TABLE IF EXISTS "+EXERCISE_TAB_NAME);
//			 db.execSQL("DROP TABLE IF EXISTS "+TASKS_TAB_NAME);

			db.execSQL("CREATE TABLE IF NOT EXISTS " + EXERCISE_TAB_NAME
					+ " (id INTEGER PRIMARY KEY,name varchar(255) UNIQUE);");
			db.execSQL("CREATE TABLE IF NOT EXISTS "
					+ TASKS_TAB_NAME
					+ " (id INTEGER PRIMARY KEY,exercise VARCHAR(255),number INTEGER, time LONG, generated INTEGER);");

			for (int i = 0; i < baseExercises.length; i++) {
				db.execSQL("INSERT OR REPLACE INTO " + EXERCISE_TAB_NAME
						+ " VALUES (null,'" + baseExercises[i] + "');");

			}

		}
	}

	public static void showtable(String name) {

		Cursor cursor = db.rawQuery("select * from " + name, null);
		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {
			do {
				Log.d("db", cursor.getString(0) + "  " + cursor.getString(1));
			} while (cursor.moveToNext());
		}
		cursor.close();
	}

	public static void closeDataBase() {
		db.close();
	}

	public static String[] convertCursorToArray(String query) {
		ArrayList<String> list = new ArrayList<String>();
		Cursor cursor = db.rawQuery(query, null);
		cursor.moveToFirst();
		int colIndex = cursor.getColumnIndex("name");
		if (!cursor.isAfterLast()) {
			do {
				list.add(cursor.getString(colIndex));
			} while (cursor.moveToNext());
		}
		cursor.close();
		return (String[]) list.toArray(new String[0]);
	}

	public static ArrayList<Task> convertCursorToListOfArrays(String query) {
		ArrayList<Task> data = new ArrayList<Task>();
		Cursor cursor = db.rawQuery(query, null);
		cursor.moveToFirst();
		if (!cursor.isAfterLast()) {
			do {
				Task newTask = new Task(Integer.parseInt(cursor.getString(0)),
						cursor.getString(1), Integer.parseInt(cursor
								.getString(2)), Long.parseLong(cursor
								.getString(3)));
				data.add(newTask);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return data;
	}
}
